package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.HistorySearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.pojos.ApUserSearch;
import com.heima.search.service.ApUserSearchService;
import com.heima.utils.common.AppThreadLocalUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ApUserSearchServiceImpl implements ApUserSearchService {

    @Autowired
    private MongoTemplate mongoTemplate;
    /**
     * 保存用户搜索历史记录
     *
     * @param keyword 搜索的关键字
     * @param userId 用户的id
     */
    @Override
    @Async
    public void insert(String keyword, Integer userId) {
        //1. 根据用户的id和关键字查询搜索记录
        ApUserSearch userSearch = mongoTemplate.findOne(Query.query(Criteria.where("userId").is(userId).and("keyword").is(keyword)), ApUserSearch.class);
        //2. 如果存在则更新时间并结束请求
        if(null != userSearch){
            userSearch.setCreatedTime(new Date());
            mongoTemplate.save(userSearch);
            return;
        }

        //3. 根据用户id查询当前用户的所有的搜索记录
        List<ApUserSearch> list = mongoTemplate.find(Query.query(
                Criteria.where("userId").is(userId)).with(
                        Sort.by(Sort.Direction.DESC, "createdTime")), ApUserSearch.class);

        ApUserSearch apUserSearch = new ApUserSearch();
        apUserSearch.setCreatedTime(new Date());
        apUserSearch.setKeyword(keyword);
        apUserSearch.setUserId(userId);

        //4. 如果搜索记录小于10 则直接添加记录
        if(null == list || list.size() < 10){
            mongoTemplate.save(apUserSearch);
        }else{
            //5. 如果搜索记录大于等于10 则替换最老的记录
            mongoTemplate.findAndReplace(Query.query(Criteria.where("id").is(list.get(list.size() - 1).getId())), apUserSearch);
        }
    }

    /**
     * 查询登录用户的搜索历史记录
     *
     * @return
     */
    @Override
    public ResponseResult findUserSearch() {
        //1. 获取当前登录用户
        ApUser user = AppThreadLocalUtil.getUser();

        //2. 如果登录用户为空则直接返回成功
        if(null == user){
            return ResponseResult.okResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //3. 如果有则根据用户id查询并通过时间降序排序
        List<ApUserSearch> list = mongoTemplate.find(
                Query.query(Criteria.where("userId").is(user.getId()))
                        .with(Sort.by(Sort.Direction.DESC, "createdTime")), ApUserSearch.class);

        return ResponseResult.okResult(list);
    }

    /**
     * 根据文档的id删除文档数据
     *
     * @param historySearchDto
     * @return
     */
    @Override
    public ResponseResult del(HistorySearchDto historySearchDto) {
        //1. 参数校验
        if(StringUtils.isEmpty(historySearchDto.getId())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //2. 根据id删除文档数据
        mongoTemplate.remove(Query.query(Criteria.where("id").is(historySearchDto.getId())),  ApUserSearch.class);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
